package com.apexsoft.assets.base.convert;


import com.apexsoft.assets.base.utils.ValidateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.core.Converter;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Slf4j
public class FormatDateConverter implements Converter {

    //日期转换格式
    private String pattern = "yyyy-MM-dd HH:mm:ss";
    private String numberPattern = "yyyyMMdd";
    private SimpleDateFormat sdf = null;
    private SimpleDateFormat numberSdf = new SimpleDateFormat(numberPattern);

    public FormatDateConverter() {
        sdf = new SimpleDateFormat(pattern);
    }

    public FormatDateConverter(String pattern) {
        this.pattern = pattern;
        sdf = new SimpleDateFormat(pattern);
    }

    public void setPattern(String pattern){
        this.pattern = pattern;
        sdf = new SimpleDateFormat(pattern);
    }

    @Override
    // value 源对象属性，target 目标对象属性类，context 目标对象setter方法名
    public Object convert(Object value, Class target, Object context) {
        if(value instanceof Date){
            return sdf.format(value);
        }else if(value instanceof Number){
            ValidateUtil.isDate((Number)value,"yyyyMMdd");
            try{
                return sdf.format(numberSdf.parse(value.toString()));
            }catch (Exception e){
                log.error("Date Format ERROR: ", e);
               e.printStackTrace();
            }
            return String.valueOf(value);
        }
        return value;
    }

}
